package com.demo;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.otto.Subscribe;

import java.util.HashMap;
import java.util.Map;

import com.hcvsa.HCVSAService;
import com.hcvsa.MyHCVSA;
import com.hcvsa.OnCMSLoginResult;
import com.hcvsa.ReturnMeetingRoomInfo;
import com.hcvsa.UserCallInvite;
import com.hcvsa.UserOnline;
import com.until.BusProvider;
import com.until.PermissionUtil;
import fun.flyee.pengshan.social.R;
import hcvs.audio.AudioPlay;
import hcvs.hcvca.bean.MeetingRoom;
import hcvs.hcvsa.SystemEvent;

public class MainActivity1 extends Activity implements OnClickListener {

    private Button btn_login;
    private Button btn_logoff;
    private Button btn_call;
    private Button btn_monitor;
    private Button btn_meeting;
    private Button btn_get_meeting;

    private TextView tv_cms_log;
    private TextView tv_login_result;

    private EditText edit_ip;
    private EditText edit_account;
    private EditText edit_pass;
    private EditText edit_channelid;
    private EditText edit_sessionid;
    private EditText edit_meetingid;

    private boolean isServiceInit = false;
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder serviceBinder) {
            isServiceInit = true;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);
        BusProvider.getInstance().register(this);
        findView();
        init();
        serviceInit();

        /* ------------注意-------------  */
        /*使用时请确保应用具备相关权限 */
        PermissionUtil.isNeedRequestPermission(MainActivity1.this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        BusProvider.getInstance().unregister(this);
        unbindService(conn);
        super.onDestroy();
    }

    private void findView() {
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_logoff = (Button) findViewById(R.id.btn_logoff);
        btn_call = (Button) findViewById(R.id.btn_call);
        btn_monitor = (Button) findViewById(R.id.btn_monitor);
        btn_meeting = (Button) findViewById(R.id.btn_meeting);
        btn_get_meeting = (Button) findViewById(R.id.btn_get_meeting);

        edit_ip = (EditText) findViewById(R.id.edit_ip);
        edit_account = (EditText) findViewById(R.id.edit_account);
        edit_pass = (EditText) findViewById(R.id.edit_pass);
        edit_channelid = (EditText) findViewById(R.id.edit_channelid);
        edit_sessionid = (EditText) findViewById(R.id.edit_sessionid);
        edit_meetingid = (EditText) findViewById(R.id.edit_meetingid);

        tv_cms_log = (TextView) findViewById(R.id.cms_log);
        tv_login_result = (TextView) findViewById(R.id.login_result);

        btn_login.setOnClickListener(this);
        btn_logoff.setOnClickListener(this);
        btn_call.setOnClickListener(this);
        btn_monitor.setOnClickListener(this);
        btn_meeting.setOnClickListener(this);
        btn_get_meeting.setOnClickListener(this);
    }

    private void init() {
        edit_ip.setText("hcvs.tpddns.cn");        //登录服务器的地址
        edit_account.setText("tb21");            //登录账号
        edit_pass.setText("123");                //登录密码
        edit_channelid.setText("655");            //打开视频监控的ID号

        //采用AudioTrack音频解码，改变设置需重新调用OnCMSCreate方法才生效
        AudioPlay.setM_audio_play_mode(AudioPlay.CONFIG_AUDIO_PLAY_MODE_AUDIO_TRACK);
        //采用OpenSL ES音频解码，改变设置需重新调用OnCMSCreate方法才生效
        //AudioPlay.setM_audio_play_mode(AudioPlay.CONFIG_AUDIO_PLAY_MODE_OPENSL);

    }

    /**
     * 用户邀请音视频通话
     *
     * @param data
     */
    @Subscribe
    public void UserCallInvite(UserCallInvite data) {
        int sessionid = data.getSessionid();
        if (sessionid == 0) return;

        Intent intent = new Intent(MainActivity1.this, VideoActivity.class);
        intent.putExtra("sessionid", sessionid);
        intent.putExtra("isMyCall", false);
        startActivity(intent);
    }

    //一个用户上线了。
    @Subscribe
    public void OnUserOnline(UserOnline data) {
        int sessionid = data.getUser().getSessionid();
        String username = data.getUser().getName();
        String logStr = "用户" + username + "上线,sessionid=" + sessionid;
        AddLogText(logStr);
        edit_sessionid.setText(sessionid + "");
    }

    //服务器返回登录的结果
    @Subscribe
    public void OnCMSLoginResult(OnCMSLoginResult data) {
        if (data.getLoginResult() == SystemEvent.HCVS_LOGIN_RESULT_OK) {
            tv_login_result.setText("登录结果:登录成功.");
            // 当登录成功并且Activity初始化完成后调用此函数，通知服务端已经初始化完成，这时服务端就会发送在线用户信息等数据
            MyHCVSA.getInstance().CMSConnectActivity();
        } else if (data.getLoginResult() == SystemEvent.HCVS_LOGIN_RESULT_LOGIN_INIT_OVER) {
            tv_login_result.setText("登录结果:登录成功(初始化完成).");
        } else {
            tv_login_result.setText("登录结果:登录失败,错误码:" + data.getLoginResult() + "!");
        }
    }

    //绑定服务
    private void serviceInit() {
        Intent serviceIntent = new Intent(this, HCVSAService.class);
        bindService(serviceIntent, conn, Service.BIND_AUTO_CREATE);
    }

    public void AddLogText(String log) {
        String tv_text;
        tv_text = tv_cms_log.getText().toString() + "\n" + log;
        tv_cms_log.setText(tv_text);
    }

    @Override
    public void onClick(View v) {
        if (isServiceInit == false) {
            Toast.makeText(MainActivity1.this, "未初始化完毕。。", Toast.LENGTH_LONG).show();
            return;
        }
        switch (v.getId()) {
            case R.id.btn_login:
                MyHCVSA.getInstance().OnCMSCreate(edit_ip.getText().toString(), 9901, edit_account.getText().toString(), edit_pass.getText().toString());
                break;
            case R.id.btn_logoff:
                MyHCVSA.getInstance().OnCMSDestroy();
                break;
            case R.id.btn_call:
                String sessionidString = edit_sessionid.getText().toString().trim();
                int sessionid = Integer.parseInt(sessionidString);
                if (sessionid == 0) return;

                Intent intent = new Intent(MainActivity1.this, VideoActivity.class);
                intent.putExtra("sessionid", sessionid);
                intent.putExtra("isMyCall", true);
                startActivity(intent);

                break;
            case R.id.btn_monitor:
                int channelid = Integer.parseInt(edit_channelid.getText().toString());
                Intent intent2 = new Intent(MainActivity1.this, MonitorActivity.class);
                intent2.putExtra("channelid", channelid);
                startActivity(intent2);
                break;
            case R.id.btn_get_meeting:
                //获取会议室列表
                MyHCVSA.getInstance().getMeetingMoudle().RequestMeetingList(0);
                break;
            case R.id.btn_meeting:
                String sMeetingid = edit_meetingid.getText().toString();
                if (sMeetingid != null && !sMeetingid.equals("")) {
                    int meetingid = Integer.parseInt(sMeetingid);
                    Intent intent3 = new Intent(MainActivity1.this, MeetingActivity.class);
                    intent3.putExtra("meetingid", meetingid);
                    startActivity(intent3);
                }

                break;
        }

    }

    /**
     * 返回会议列表
     *
     * @param
     */
    @Subscribe
    public void ReturnMeetingRoomInfo(ReturnMeetingRoomInfo data) {

        MeetingRoom meetingRoom = data.getMeetingRoom();
        Map<String, String> meetingMap = new HashMap<String, String>();
        meetingMap.put("meetingName", meetingRoom.getRoomName());
        meetingMap.put("meetingHost", "主持人:" + meetingRoom.getHostName());
        meetingMap.put("meetingUserCount", Integer.toString(meetingRoom.getOnlineNumber()) + "人在线");
        meetingMap.put("meetingRoomId", Integer.toString(meetingRoom.getId()));
        meetingMap.put("isPassword", Integer.toString(meetingRoom.getIsPassword()));

        Log.d("meeting", "返回会议室列表name=" + meetingRoom.getRoomName() + ", id=" + meetingRoom.getId());

        edit_meetingid.setText("" + meetingRoom.getId());
    }

}
